import axios from 'axios'
import { getRedirectPath } from '@/utils'

const REGISTER = 'REGISTER'
const RESET = 'RESET'
const LOGIN = 'LOGIN'
const USER_DATA = 'USER_DATA'
const UPDATE = 'UPDATE'
const initState = {
    user: {
        _id: '',
        username: '',
        type: '',
        avatar: ''
    },
    message: '',
    code: -1,
    redirect: ''
}
//reducer
export function user(state={...initState}, action){
    switch (action.type){
        case LOGIN:
            return { ...state, ...action.payload, redirect: getRedirectPath(action.payload.user ? action.payload.user : {}) }
        case REGISTER:
            return { ...state, ...action.payload, redirect: getRedirectPath(action.payload.user ? action.payload.user : {}) }
        case RESET:
            return { ...state, ...initState }
        case USER_DATA:
            return { ...state, user: action.payload }
        case UPDATE:
            return { ...state, ...action.payload, redirect: getRedirectPath(action.payload.user) }
        default:
            return state
    }
}

export function login(data){
    return dispatch => {
        axios.post('/user/login', { ...data })
            .then( res => {
                dispatch({ type: LOGIN, payload: res.data })
            })
    }
}

export function register(data){
    return dispatch => {
        axios.post('/user/register', { ...data })
            .then( res => {
                dispatch({
                    type: REGISTER,
                    payload: res.data
                })
            })
    }
}

export function userReset(){
    return { type: RESET }
}

export function save(data){
    return { type: USER_DATA, payload: data }
}

export function update(data){
    return dispatch => {
        axios.post('/user/update', data)
            .then(res => {
                dispatch({type: UPDATE, payload: res.data})
            })
    }
}

















